<script setup lang="ts">
import { onMounted, onUnmounted, onUpdated, reactive, ref, h } from "vue";
import { useRouter } from "vue-router";
// http://github.xyxiao.cn/vue-cropper/
import 'vue-cropper/dist/index.css'
import { VueCropper }  from "vue-cropper";
import {
  NFlex,
  NCard,
  NDropdown,
  NButton,
  NTag,
  NSelect,
  NButtonGroup,
  NColorPicker,
  NSpace,
  NIcon,
  NInput, NSwitch, NInputNumber,
  NCountdown,
  type CountdownInst,
  NText,
  NModal,
} from "naive-ui";
import { createDiscreteApi } from "naive-ui";
const { message } = createDiscreteApi(["message"])
import SvgIcon from "../components/SvgIcon.vue";
import { FORM_ADD } from "@/service/apis/from";

const router = useRouter();

interface App {
  名称: string
  缩写: string
  路由?: string
  图标?: string
  类型?: string
}

//接收props
const props = defineProps({
  title: {
    type: String,
    default: "在线word协同", // 默认值
  },
  icon: {
    type: String,
    default: "Word-Color", // 默认值
  },
  fileData: {
    type: Object,
    default: undefined // 默认值
  },
  mode: {
    type: String,
    default: 'create' // 默认值
  },
  currentApp: {
    type: Object as () => App,
    default: {}// 默认值
  },
  editFileName: {
    type: String,
    default: undefined // 默认值
  },
});

const hasAnnotations = ref(false);
const annotations = reactive<Annotations[]>([]);
const AUTO_SAVE_TIME = 60 * 1000; // 自动保存时间 ms
let editFileNameMode = ref(false);
const countdownRef = ref<CountdownInst | null>()
let inputFileName = ref(props.editFileName);
let saveMode = props.editFileName ? "cover" : "new-create";
let oneMinInterval: any;
let autoSaveHappened = ref(false)
let userEditAfterSave = ref(false); // 用户编辑是否在自动保存之后
const startInterval = () => {
  oneMinInterval = setInterval(() => {
    console.log('1min-save 定时 保存')
    saveScript();
    autoSaveHappened.value = true; // 曾经发生过自动保存
    userEditAfterSave.value = false // 保存后，将用户编辑设为false
    countdownRef.value?.reset() // 重置倒计时
    saveMode = 'cover' // 后续保存都为覆盖模式
    clearInterval(oneMinInterval!);
    oneMinInterval = undefined;
  }, AUTO_SAVE_TIME);
}
const initCanvasEventListener = () => {
  canvaseditor.value?.eventBus.on('contentChange', () => {
    userEditAfterSave.value = true // 自动保存后用户又进行了编辑
    if (oneMinInterval === undefined) {
      console.log('编辑过，并且目前没有定时器，启动定时')
      startInterval()
    }
  })
}

const killInterval = () => {
  clearInterval(oneMinInterval!);
};

onUnmounted(() => {
  killInterval();
});

/**
 * canvas-editor 组件库引用
 * 实现 word 功能
 */
import Editor, {
  ControlType,
  EditorMode,
  ElementType,
  RowFlex,
  TitleLevel,
  type IRange,
  PaperDirection
} from "@hufe921/canvas-editor";

/**
 * end
 */

let wordEditor = ref<HTMLDivElement | any>(null);
const showModal = ref(false);
const cropper = ref();
const imgBase64 = ref("");
const imgHeight = ref(0);
const imgWidth = ref(0);

/**
 * 测试 CSV 解析 函数
 */
const callNodeScript = () => {
  /*
   * 实现CSV 解析转JSON 的功能
   */
  //  let str = "id;类型;时间;创建人;人员\\n84545457875845;预约;2024-09-12 15:46:30;创建人;[{'id':'63ba5f021575d240','工号':'0001','姓名':'wang','职务':'','部门':'发达食品公司','流地址':'webrtc://216.fdmf.com:1990/meeting/deee4221fc45e051/0001'}]\\n"
  //   // let str = "第一列;第二列;第三列;第四列\\n 13;[{fk:df,dff:dd},{fk:df,dff:dd}];45;34\\n 13;[{fk:df,dff:dd},{fk:df,dff:dd}];45;34\\n 13;[{fk:df,dff:dd},{fk:df,dff:dd}];45;34"
  //   let fst = str.replace(/\\n/g,"\n")
  //   console.log(fst)
  //   const ddf = Papa.parse(fst,{header:true,delimiter:";",newline:"\n"})
  //   console.log(ddf)

  let jsonstr =
    "[{'id':'63ba5f021575d240','工号':'0001','姓名':'wang','职务':'','部门':'发达食品公司','流地址':'webrtc://216.fdmf.com:1990/meeting/deee4221fc45e051/0001'}]";
  let fst = jsonstr.replace(/\'/g, '"');
  // console.log(JSON.parse(jsonstr))
  console.log(JSON.stringify(fst));
  let jsonlists = JSON.parse(fst);
  console.log(jsonlists);
  console.log("测试输出");
  // worker.postMessage("fdfdfd")
  // worker.onmessage = (e) => {
  //   console.log("dfjdjfkd",e)
  // }
};

/**
 * 构建 SSE 事件监听连接 函数
 */
//创建SSE连接事件监听
const eventSource = ref<EventSource | null>(null);
const connectToSSE = () => {
  eventSource.value = new EventSource(
    "http://localhost:8080/sse/test/fd?token=dkkjfksjkdjkfjs"
  );
  eventSource.value.onopen = (event) => {
    console.log("SSE 开启事件", event);
  };
  eventSource.value.onmessage = (event) => {
    console.log("sse 数据包", event);
  };
  eventSource.value.onerror = (error) => {
    console.log("SSE 错误信息", error);
  };
  const closeSSE = () => {
    if (eventSource.value) {
      eventSource.value.close();
      eventSource.value = null;
    }
  };
  return { closeSSE };
};
/**
 * end
 */

/**
 * 定义 word 组件相关的操作函数
 */
let canvaseditor = ref<Editor | null>(null);

//保存word
const saveScript = () => {
  const wordValue = canvaseditor.value?.command.getValue();
  const extraSettings = {
    annotations,
  };
  saveWord(wordValue, extraSettings)
};

function saveWord(content: any, extraSettings: any) {
  console.log('保存', props.currentApp['名称'], inputFileName.value)
  let data = {
    类型: "数据",
    内容: {
      应用名称: props.currentApp['名称'],
      类型: "word",
      名称: inputFileName.value,
      内容: { content, extraSettings }
      // 新增还是覆盖: "新增",
    }
  }
  FORM_ADD({ "params": JSON.stringify(data) }).then((res: any) => {
    if (res.stacode == 200) {
      console.log(res);
      message.success('保存已提交')
    }
  }).catch((err: any) => {
    console.log('err', err);

  })
}


//设置word 只读状态
const onlayScript = () => {
  canvaseditor.value?.command.executeMode(EditorMode.READONLY);
};
//设置word 编辑设计状态
const closeonlay = () => {
  canvaseditor.value?.command.executeMode(EditorMode.DESIGN);
};
// 复制
const copy = () => {
  canvaseditor.value?.command.executeCopy();
};
// 剪切
const cut = () => {
  canvaseditor.value?.command.executeCut();
};
// 粘贴
const paste = () => {
  canvaseditor.value?.command.executePaste();
};
/**
 * 格式刷
 */
// 格式复制
const copyFormat = () => {
  canvaseditor.value?.command.executePainter({ isDblclick: false });
};
//格式清除
const closeformat = () => {
  canvaseditor.value?.command.executeFormat();
};

interface Annotations {
  pageNo: number;
  rowNo: number;
  index: number;
  text: string;
  groupId: string;
  time: string;
  timestamp: number;
  content?: string;
  range?: IRange
}
//设置批注
const onSetAnnotations = () => {
  const range = canvaseditor.value?.command.getRange();
  const rangeText = canvaseditor.value?.command.getRangeText();
  const cursorPosition = canvaseditor.value?.command.getCursorPosition()
  console.log('选区', range, rangeText, cursorPosition);
  const { pageNo, rowNo, index } = cursorPosition!
  // canvaseditor.value?.command.executeHighlight('#EFB666');
  addAnnotation({
    pageNo,
    rowNo,
    index,
    range,
    groupId: canvaseditor.value?.command.executeSetGroup()!,
    text: rangeText || "",
    time: new Date().toLocaleString(),
    timestamp: new Date().getTime(),
  });
};

const onClickAnnotation = (item: Annotations) => {
  console.log('点击批注', item);
  const { groupId } = item;
  canvaseditor.value?.command.executeLocationGroup(groupId);
}

const onDelAnnotation = (groupId: string) => {
  // const annotation = annotations.find((item) => item.groupId === groupId);
  // const {
  //   startIndex,
  //   endIndex,
  //   tableId
  // } = annotation!.range!
  // canvaseditor.value?.command.executeSetRange(startIndex, endIndex, tableId);
  // canvaseditor.value?.command.executeHighlight('#FFFFFF');
  canvaseditor.value?.command.executeDeleteGroup(groupId);
  const annotationIndex = annotations.findIndex((item) => item.groupId === groupId);
  annotations.splice(annotationIndex, 1);
}

// 定义一个比较函数，用于确定新注解应该插入的位置  
const compareAnnotations = (a: Annotations, b: Annotations): number => {
  if (a.pageNo !== b.pageNo) {
    return a.pageNo - b.pageNo;
  }
  if (a.rowNo !== b.rowNo) {
    return a.rowNo - b.rowNo;
  }
  return a.index - b.index;
};
const addAnnotation = (annotation: Annotations) => {
  hasAnnotations.value = true;
  
  // 遍历注解数组，找到插入位置  
  let insertIndex = 0;  
  while (insertIndex < annotations.length && compareAnnotations(annotations[insertIndex], annotation) < 0) {  
    insertIndex++;  
  }  
  
  // 使用splice方法在找到的位置插入新注解  
  annotations.splice(insertIndex, 0, annotation);  
};
/**
 * end
 */

const fdmenu = () => { };
/**
 * 左侧面板操作函数
 */
const activeLeftPlane = ref(false);
const closeLeftPlane = () => {
  activeLeftPlane.value = false;
};

/**
 * end
 */
/**
 * 定义格式面板相关的操作函数
 */
const activePlane = ref(true);
const textColor = ref("#000"); // 文本颜色
const showPlane = () => {
  activePlane.value = activePlane.value ? false : true;
  textPlane.value = false;
};

const textPlane = ref(false);
const textShow = () => {
  textPlane.value = textPlane.value ? false : true;
  activePlane.value = false;
};
/**
 * end
 *
 */
const titleValue = ref();
const titleOptions = [
  { label: "标题1", value: "h1" },
  { label: "标题2", value: "h2" },
  { label: "标题3", value: "h3" },
  { label: "标题4", value: "h4" },
  { label: "标题5", value: "h5" },
  { label: "标题6", value: "h6" },
];

const titleSelect = (value: string) => {
  console.log(value);
  titleValue.value = value;
  switch (value) {
    case "h1":
      canvaseditor.value?.command.executeTitle(TitleLevel.FIRST);
      break;
    case "h2":
      canvaseditor.value?.command.executeTitle(TitleLevel.SECOND);
      break;
    case "h3":
      canvaseditor.value?.command.executeTitle(TitleLevel.THIRD);
      break;
    case "h4":
      canvaseditor.value?.command.executeTitle(TitleLevel.FOURTH);
      break;
    case "h5":
      canvaseditor.value?.command.executeTitle(TitleLevel.FIFTH);
      break;
    case "h6":
      canvaseditor.value?.command.executeTitle(TitleLevel.SIXTH);
      break;
    default:
      break;
  }
};


const paperSizeValue = ref('a4');
const paperSizeOptions = [
  { label: "A4", value: "a4" },
  // { label: "A2", value: "a2" },
  { label: "A3", value: "a3" },
  { label: "A5", value: "a5" },
  { label: "5号信封", value: "no5" },
  { label: "6号信封", value: "no6" },
  { label: "7号信封", value: "no7" },
  { label: "9号信封", value: "no9" },
  { label: "法律用纸", value: "law" },
  { label: "信纸", value: "letter" },

];

const paperSizeSelect = (value: string) => {
  // https://github.com/Hufe921/canvas-editor/blob/main/index.html#L400
  // <li data-paper-size="794*1123">A4</li>
  // <li data-paper-size="1593*2251">A2</li>
  // <li data-paper-size="1125*1593">A3</li>
  // <li data-paper-size="565*796">A5</li>
  // <li data-paper-size="412*488">5号信封</li>
  // <li data-paper-size="450*866">6号信封</li>
  // <li data-paper-size="609*862">7号信封</li>
  // <li data-paper-size="862*1221">9号信封</li>
  // <li data-paper-size="813*1266">法律用纸</li>
  // <li data-paper-size="813*1054">信纸</li>
  paperSizeValue.value = value;
  const { width, height } = {
    a4: { width: 794, height: 1123 },
    a2: { width: 1593, height: 2251 },
    a3: { width: 1125, height: 1593 },
    a5: { width: 565, height: 796 },
    no5: { width: 412, height: 488 },
    no6: { width: 450, height: 866 },
    no7: { width: 609, height: 862 },
    no9: { width: 862, height: 1221 },
    law: { width: 813, height: 1266 },
    letter: { width: 813, height: 1054 },
  }[value] || { width: 794, height: 1123 };

  canvaseditor.value?.command.executePaperSize(width, height);
};

let valuefont = ref();
const fontoptions = [
  { label: "微软雅黑", value: "微软雅黑" },
  { label: "宋体", value: "宋体" },
  { label: "黑体", value: "黑体" },
  { label: "Arial", value: "Arial" },
  { label: "Verdana", value: "Verdana" },
  { label: "Times New Roman", value: "Times New Roman" },
  { label: "Georgia", value: "Georgia" },
  { label: "Courier New", value: "Courier New" },
  { label: "Tahoma", value: "Tahoma" },
  { label: "Trebuchet MS", value: "Trebuchet MS" },
  { label: "Palatino Linotype", value: "Palatino Linotype" },
  { label: "Garamond", value: "Garamond" },
  { label: "Courier", value: "Courier" },
];

const onblur = (value: string) => {
  console.log(value);
  valuefont.value = value;
  // canvaseditor.value?.command.executeSize(36)
  canvaseditor.value?.command.executeFont(value);
};

let valuesize = ref();
const dffsize = [
  { label: "小初", value: 48 },
  { label: "一号", value: 34 },
  { label: "小一", value: 32 },
  { label: "二号", value: 29 },
  { label: "小二", value: 24 },
  { label: "三号", value: 21 },
  { label: "小三", value: 20 },
  { label: "12", value: 12 },
  { label: "14", value: 14 },
  { label: "16", value: 16 },
  { label: "18", value: 18 },
  { label: "22", value: 22 },
  { label: "26", value: 26 },
  { label: "36", value: 36 },
  { label: "38", value: 38 },
  { label: "40", value: 40 },
  { label: "42", value: 42 },
  { label: "44", value: 44 },
  { label: "46", value: 46 },
  { label: "50", value: 50 },
  { label: "52", value: 52 },
];

const onsize = (value: number) => {
  // console.log(value)
  valuesize.value = value;
  canvaseditor.value?.command.executeSize(value);
};

// 字体加粗
const bold = () => {
  canvaseditor.value?.command.executeBold();
};

// 下划线
const underline = () => {
  canvaseditor.value?.command.executeUnderline();
};
// 删除线
const delete_line = () => {
  canvaseditor.value?.command.executeStrikeout();
};
// 斜体
const italic = () => {
  canvaseditor.value?.command.executeItalic();
};
// 对齐方法
const alignment = (rowFlex: RowFlex) => {
  canvaseditor.value?.command.executeRowFlex(rowFlex);
};

// 字体颜色更改
const editTextColor = (color: string | null) => {
  canvaseditor.value?.command.executeColor(color);
};

// 上标
const Superscript = () => {
  canvaseditor.value?.command.executeSuperscript();
};
// 下标
const Subscript = () => {
  canvaseditor.value?.command.executeSubscript();
};

/**
 * end
 */

/**
 * 初始 word 组件库加载函数
 */
onMounted(() => {
  //实例化 Editor 构建函数 word 组件库
  canvaseditor.value = new Editor(
    wordEditor.value,
    {
      header: [
        {
          value: "山东发达面粉集团",
          size: 32,
          color: "#FF0000",
          rowFlex: RowFlex.JUSTIFY,
        },
        {
          value: "\n",
          type: ElementType.SEPARATOR,
        },
      ],
      main: [
        {
          value: "",
        },
      ],
      footer: [
        {
          value: "\n",
          type: ElementType.SEPARATOR,
        },
        {
          value: "集团地址：山东省济南市西城大厦10F",
          size: 18,
        },
      ],
    },
    {
      // mode: EditorMode.DESIGN,
      margins: [100, 80, 100, 80],
      zone: { tipDisabled: false },
      defaultType: "TABLE",
      maskMargin: [60, 0, 30, 0],
      defaultSize: 22,
      header: { top: 40 },
      footer: { bottom: 70 },
    }
  );

  // docxeditor.value
  console.log("word 文档");

  initCanvasEventListener();
  updateCanvasMenu();
});

const updateCanvasMenu = () => {
  canvaseditor.value?.register.contextMenuList([
  {
      key: "insert-image",
      name: "插入图片",
      // icon: "image",
      icon: "insert-top-row", // 图标列表（并非全部可用） https://github.com/Hufe921/canvas-editor/tree/main/src/editor/assets/images
      callback: () => {
        const imageFileDom = document.querySelector<HTMLInputElement>('#image')!
        imageFileDom.click()
        imageFileDom.onchange = function () {
          const file = imageFileDom.files![0]!
          const fileReader = new FileReader()
          fileReader.readAsDataURL(file)
          fileReader.onload = function () {
            // 计算宽高
            const image = new Image()
            const value = fileReader.result as string
            image.src = value
            image.onload = function () {
              canvaseditor.value?.command.executeImage({
                value,
                width: image.width,
                height: image.height
              })
              imageFileDom.value = ''
            }
          }
        }
      },
      when: () => true
    },
    {
      key: "cut-image",
      name: "图片裁切",
      icon: "image-change",
      callback: (command: any, context: any) => {
        if (context.endElement?.type === ElementType.IMAGE){
          console.log("图片裁切", context)
          showModal.value = true;
          imgBase64.value = context.endElement.value;
          imgHeight.value = context.endElement.height;
          imgWidth.value = context.endElement.width;
        }
      },
      when: (context: any) => { // 是否在图片上右键
        if (context.endElement?.type === ElementType.IMAGE){
          return true;
        }
        return false;
      }
    },
  ])
  console.log("当前所有右键菜单", canvaseditor.value?.register.getContextMenuList())
};

let oldFileData: Object | undefined = undefined
onUpdated(() => {
  if (props.mode === 'update') {
    if (oldFileData !== props.fileData) {
      console.log('更新数据', props)
      const { content , extraSettings } = props.fileData!
      canvaseditor.value?.command.executeSetValue(content.data)
      oldFileData = props.fileData
      const { annotations } = extraSettings
      console.log('批注数据', annotations)
      annotations.forEach((item: any) => addAnnotation(item))
      
    }
  }
});

//插件单选控件

const single = () => {
  canvaseditor.value?.command.executeInsertControl({
    type: ElementType.CONTROL,
    control: {
      conceptId: "3",
      type: ControlType.RADIO,
      code: "98175",
      value: [],
      valueSets: [
        {
          value: "同意",
          code: "98175",
        },
        {
          value: "否定",
          code: "98176",
        },
      ],
    },
    value: "",
  });
};

//插件多选控件
const selectCL = () => {
  canvaseditor.value?.command.executeInsertControl({
    type: ElementType.CONTROL,
    value: "",
    control: {
      conceptId: "2",
      type: ControlType.SELECT,
      value: null,
      code: null,
      placeholder: "有无",
      prefix: "{",
      postfix: "}",
      valueSets: [
        {
          value: "有",
          code: "98175",
        },
        {
          value: "无",
          code: "98176",
        },
        {
          value: "不详",
          code: "98177",
        },
      ],
    },
  });
};

//插入日期控件
const dftest = () => {
  canvaseditor.value?.command.executeInsertControl({
    type: ElementType.CONTROL,
    value: "",
    control: {
      conceptId: "5",
      type: ControlType.DATE,
      value: [
        {
          value: `2022-08-10 17:30:01`,
        },
      ],
      placeholder: "签署日期",
    },
  });
};

const fftest = () => {
  canvaseditor.value?.command.executeInsertControl({
    type: ElementType.RADIO,
    checkbox: {
      value: false,
    },
    value: "是的",
  });
};
/**
 * end
 */


/**
 * 头部标题图标设置
 * 头标下拉菜单设置
 */
const options_word = [
  { label: "保存", key: "保存" },
  { label: "导出pdf", key: "导出pdf" },
  { label: "打印", key: "打印" },
];
const wordSelect = (key: string) => {
  console.log(key);
  if (key === "保存") {
    saveScript()
  }
};
let wordIcon = () => {
  return h(NFlex, () => [
    h(
      NDropdown,
      {
        trigger: "hover",
        size: "huge",
        showArrow: true,
        options: options_word,
        onSelect: wordSelect,
      },
      () =>
        h(NButton, { text: true, style: "font-size: 24px" }, () =>
          h(SvgIcon, { iconClass: props.icon })
        )
    ),
    h("div", props.title),
    h("div", { style: "display: flex; align-items: center;font-size: 14px; margin-left: 30px; " }, [
      h('div', { style: "color: green;" }, '文件名：'),
      editFileNameMode.value ? undefined : h(SvgIcon, { iconClass: 'bianji', style: "font-size: 26px;", onClick: () => { editFileNameMode.value = true } },),
      h("div", { style: "min-width: 210px" },
        editFileNameMode.value ? h(NInput, {
          placeholder: '文件未命名',
          size: 'small',
          style: 'height: 28px; width: 200px;',
          maxlength: 30,
          showCount: true,
          // 注意：v-model 在渲染函数中需要拆分为 value 属性和 onInput 事件监听器  
          value: inputFileName.value, // 假设 inputFileName 是组件的 data 属性  
          onInput: (event) => { inputFileName.value = event },
          onBlur: () => { editFileNameMode.value = false }
        },) : h('div', { style: inputFileName.value ? "" : "color:lightgray", onClick: () => { editFileNameMode.value = true } }, inputFileName.value || "文件未命名"),
      ),

    ]),
    autoSaveHappened.value ? h(NTag, { type: "success", bordered: false }, () => "已自动提交保存") :
      userEditAfterSave.value ? h(NTag, { type: "warning", bordered: false }, () => "文件会每一分钟自动提交保存") : undefined,
    userEditAfterSave.value ? h("div", { style: "font-size: 12px; display: flex; align-items: center; color:gray" },
      [
        h('div', { style: "" }, '下次自动保存：'),
        h(NCountdown, { duration: AUTO_SAVE_TIME, ref: countdownRef }),
      ]) : undefined,
  ]);
};
const header_word = () => wordIcon();

// const zoomValue = 50
const newZoomValue = ref(100);
// const

const undo = () => {
  canvaseditor.value?.command.executeUndo()
}
const redo = () => {
  canvaseditor.value?.command.executeRedo()
}
const fontSizeAdd = () => {
  canvaseditor.value?.command.executeSizeAdd()
}
const fontSizeMinus = () => {
  canvaseditor.value?.command.executeSizeMinus()
}
/**
 * end
 */
/**
 * word 表格菜单
 */
const tableMenu = [
  { label: "插入流程表格", key: "a" },
  { label: "插入数据表格", key: "b" },
  { label: "插入多行多列", key: "c" },
];
const tableMenuSelect = (key: string) => {
  console.log(key);
  if (key === "a") {
    canvaseditor.value?.command.executeInsertTable(3, 2);
  } else if (key === "b") {
    canvaseditor.value?.command.executeInsertTable(3, 6);
  } else if (key === "c") {
    canvaseditor.value?.command.executeInsertTable(10, 10);
  }
};
/**
 * end
 */

/**
 * word 控件菜单
 */
const controlMenu = [
  { label: "单选", key: "单选" },
  { label: "多选", key: "多选" },
  { label: "日期", key: "日期" },
];
const controMenuSelect = (key: string) => {
  console.log(key);
  if (key === "单选") {
    single();
  } else if (key === "多选") {
    selectCL();
  } else if (key === "日期") {
    dftest();
  }
};
/**
 * end
 *
 */

/**
 * 关闭页面，原则返回上一页
 */
const handleClose = () => {
  console.log("关闭页面");
  router.go(-1);
};
const selectoptions = [
  { label: "50%", value: 3 },
  { label: "75%", value: 2 },
  { label: "100%", value: 1 },
  { label: "125%", value: 4 },
  { label: "175%", value: 5 },
];
const selectFunc = (e: number) => {
  // console.log(e)
  // canvaseditor.value?.command.executePageScaleRecovery()

  if (e == 3) {
    console.log(e);
    canvaseditor.value?.command.executePageScaleRecovery()
    for (let i = 0; i < 3; i++) {
      canvaseditor.value?.command.executePageScaleMinus()
    }


  } else if (e == 2) {
    canvaseditor.value?.command.executePageScaleRecovery()
    for (let i = 0; i < 2; i++) {
      canvaseditor.value?.command.executePageScaleMinus()
    }
  } else if (e == 1) {
    canvaseditor.value?.command.executePageScaleRecovery()
  } else if (e == 4) {
    canvaseditor.value?.command.executePageScaleRecovery()
    for (let i = 0; i < 2; i++) {
      canvaseditor.value?.command.executePageScaleAdd()
    }
  } else if (e == 5) {
    canvaseditor.value?.command.executePageScaleRecovery()
    for (let i = 0; i < 3; i++) {
      canvaseditor.value?.command.executePageScaleAdd()
    }
  }


};
/**
 * end
 */
const paperMarginTop = ref(100);
const paperMarginBottom = ref(80);
const paperMarginLeft = ref(100);
const paperMarginRight = ref(80);

const updatePageMargin = () => {
  // console.log("更新页边距", canvaseditor.value?.command.getPaperMargin(), paperMarginTop.value, paperMarginRight.value, paperMarginBottom.value, paperMarginLeft.value);
  canvaseditor.value?.command.executeSetPaperMargin([paperMarginTop.value, paperMarginRight.value, paperMarginBottom.value, paperMarginLeft.value]);
}

const changePaperDirection = (isHorizontal: boolean) => {
  const dir = isHorizontal ? PaperDirection.HORIZONTAL : PaperDirection.VERTICAL;
  canvaseditor.value?.command.executePaperDirection(dir);
}

const doCropper = () => {
  if (cropper?.value) {
    cropper.value.getCropData((data: any) => {
      console.log(data)
      // canvaseditor.value?.command.executeBackspace() // 向前删除
      canvaseditor.value?.command.executeImage({ // 插入新图片
        width: cropper.value.cropW,
        height: cropper.value.cropH,
        value: data
      })
      // canvaseditor.value?.command.executeReplaceImageElement(data) // 替换图片
      showModal.value = false;
    })
  }
}

</script>
<template>
  <n-modal v-model:show="showModal" preset="card" title="裁切"
    :style="{ width: (imgWidth + 50) + 'px', height: (imgHeight + 140) + 'px', maxHeight: '740px'}">
    <vue-cropper ref="cropper" :img="imgBase64" autoCrop
      :style="{ width: imgWidth + 'px', height: imgHeight + 'px', maxHeight: '600px' }"></vue-cropper>
    <template #footer>
      <n-button @click="doCropper">确定</n-button>
    </template>
  </n-modal>
  <input type="file" id="image" accept=".png, .jpg, .jpeg, .svg, .gif" v-show="false">
  <n-card :title="header_word" closable @close="handleClose">
    <template #header-extra>
      <n-flex justify="space-between">
        <slot name="header-extra"></slot>

        <n-button @click="onlayScript" text ghost>只读模式</n-button>
        <n-button @click="closeonlay" text ghost>设计模式</n-button>
        <button @click="fdmenu">测试图标菜单</button>
        <button @click="connectToSSE">SSE服务加载</button>
        <!-- <button @click="fetchSee">fetchSSE</button> -->
        <button @click="callNodeScript">测试</button>
        <button @click="saveScript">保存</button>
      </n-flex>
    </template>

    <n-flex vertical :size="[0, 3]">
      <n-flex justify="space-between">
        <!-- 左侧 -->
        <n-flex>
          <n-button @click="activeLeftPlane = !activeLeftPlane" text ghost style="width: 50px;">
            <template #icon>
              <n-flex vertical :size="[0, 2]" style="align-items: center;">
                <n-tag style="width: 40px; justify-content: center; display: flex;" size="small">
                  <svg-icon icon-class="liebiao" />
                </n-tag>
                <span style="font-size: 12px;">显示</span>
              </n-flex>
            </template>
          </n-button>
          <n-flex vertical :size="0" style="align-items: center;">
            <n-select style="width: 80px; " size="tiny" v-model:value="newZoomValue" :options="selectoptions"
              @update:value="selectFunc" />
            <n-text style="font-size: 12px;">缩放</n-text>
          </n-flex>
        </n-flex>
        <!-- 中间 -->
        <n-flex justify="center">
          <n-button class="btntools" @click="undo" title="撤销" text>
            <n-icon>
              <svg-icon icon-class="huanyuan" />
            </n-icon>
          </n-button>
          <n-button class="btntools" @click="redo" title="恢复" text>
            <n-icon>
              <svg-icon icon-class="zhongzuo" />
            </n-icon>
          </n-button>
          <n-button class="btntools" @click="copy" title="复制" text>
            <n-icon>
              <svg-icon icon-class="fuzhi" />
            </n-icon>
          </n-button>
          <n-button class="btntools" @click="cut" title="剪切" text>
            <n-icon>
              <svg-icon icon-class="jianqiewenjian" />
            </n-icon>
          </n-button>
          <n-button class="btntools" @click="paste" title="粘贴" text>
            <n-icon>
              <svg-icon icon-class="pastel" />
            </n-icon>
          </n-button>
          <n-button class="btntools" @click="fontSizeAdd" title="字体加大" text>
            <n-icon>
              <svg-icon icon-class="24gl-fontSizeIncrease" />
            </n-icon>
          </n-button>
          <n-button class="btntools" @click="fontSizeMinus" title="字体减小" text>
            <n-icon>
              <svg-icon icon-class="24gl-fontSizeDecrease" />
            </n-icon>
          </n-button>
          <n-button class="btntools" @click="copyFormat" title="复制格式" text>
            <n-icon>
              <svg-icon icon-class="geshishua" />
            </n-icon>
          </n-button>
          <n-button class="btntools" @click="closeformat" title="清除格式" text>
            <n-icon>
              <svg-icon icon-class="qingchuyangshi" />
            </n-icon>
          </n-button>


          <n-dropdown trigger="hover" :options="tableMenu" @select="tableMenuSelect" :show-arrow="true" size="small">
            <n-button text ghost>
              <template #icon>
                <n-flex vertical :size="[0, 2]" style="align-items: center;">
                  <n-tag style=" justify-content: center; display: flex;" size="small">
                    <svg-icon icon-class="biaoge1" />
                  </n-tag>
                  <span style="font-size: 12px;">表格</span>
                </n-flex>
              </template>
            </n-button>
          </n-dropdown>

          <n-dropdown trigger="hover" :options="controlMenu" @select="controMenuSelect" :show-arrow="true" size="small">
            <n-button text ghost style="width: 50px;">

              <template #icon>
                <n-flex vertical :size="[0, 2]" style="align-items: center;">
                  <n-tag style=" justify-content: center; display: flex;" size="small">
                    <svg-icon icon-class="charutubiao1" />
                  </n-tag>
                  <span style="font-size: 12px;">控件</span>
                </n-flex>
              </template>
            </n-button>
          </n-dropdown>
          <n-button @click="onSetAnnotations" text ghost>
            <template #icon>
              <n-flex vertical :size="[0, 2]" style="align-items: center;">
                <n-tag style=" justify-content: center; display: flex;" size="small">
                  <svg-icon icon-class="bianji3" />
                </n-tag>
                <span style="font-size: 12px;">批注</span>
              </n-flex>
            </template>
          </n-button>
        </n-flex>
        <!-- 右侧 -->
        <n-flex justify="end">
          <n-button-group size="small" style="width: 100px;">
            <n-button text @click="showPlane" ghost style="width: 50px;">
              <template #icon>
                <n-flex vertical :size="[0, 2]" style="align-items: center;">
                  <n-tag style="width: 50px; justify-content: center; display: flex;" size="small">
                    <svg-icon :icon-class="activePlane ? 'yangshi' : 'chaboxiaoxi-yangshi'" />
                  </n-tag>
                  <span style="font-size: 12px;">格式</span>
                </n-flex>
              </template>
            </n-button>
            <n-button text @click="textShow" ghost style="width: 50px;">
              <template #icon>
                <n-flex vertical :size="[0, 2]" style="align-items: center;">
                  <n-tag style="width: 50px; justify-content: center; display: flex;" size="small">
                    <svg-icon icon-class="wenjian1" />
                  </n-tag>
                  <span style="font-size: 12px;">文稿</span>
                </n-flex>
              </template>
            </n-button>
          </n-button-group>
        </n-flex>
        <!-- end -->
      </n-flex>
      <slot name="default"></slot>
      <n-flex justify="space-between">
        <n-flex>
          <div style="border: 0px solid #de1515; width: calc(100vw / 6)">
            <n-card v-show="activeLeftPlane" title="文档目录结构" style="height: 100%" closable @close="closeLeftPlane">
              <template #default> </template>

            </n-card>
          </div>
        </n-flex>
        <n-flex class="flowsss">
          <div style="border: 1px solid #de1515" ref="wordEditor"></div>
        </n-flex>
        <n-flex>
          <div v-if="hasAnnotations" class="annotationStyles">
            <template v-for="item in annotations" :key="item.time">
              <n-card v-show="activePlane" :title="item.text" embedded :bordered="false" closable
                @close="onDelAnnotation(item.groupId)" @click="onClickAnnotation(item)" style="margin-top: 10px;" content-style="padding: 0;"
                header-style="padding: 3px;">
                <span style="font-size: 12px; color: gray; margin-left: 10px">{{ item.time }}</span>
                <n-input @click.stop="console.log('编辑文本，拦截事件穿透')" type="textarea" embedded :bordered="false" rows=1 placeholder="批注内容"
                  v-model:value="item.content" @update:value="onblur" style="width: 100%" />
              </n-card>
            </template>
          </div>
        </n-flex>
        <n-flex>
          <div style="
              width: calc(100vw / 6);
              border: 0px solid #de1515;
              margin-top: 10px;
            ">
            <!-- 文稿设置 -->
            <n-card v-show="textPlane" style="height: 100%">
              <n-flex vertical :size="[0, 25]">
                <n-flex>纸张尺寸
                  <n-select v-model:value="paperSizeValue" :options="paperSizeOptions" @update:value="paperSizeSelect"
                    clearable placeholder="纸张大小" />
                </n-flex>

                <n-flex>
                  <span>页面方向</span>
                  <n-switch @update:value="changePaperDirection">
                    <template #checked>
                      横向
                    </template>
                    <template #unchecked>
                      纵向
                    </template>
                  </n-switch>
                </n-flex>
                <n-flex vertical><span>页面边距</span>
                  <n-flex>
                    <n-flex>
                      左边距
                      <n-input-number :min="40" :max="160" :step="5" v-model:value="paperMarginLeft"
                        @change="updatePageMargin"></n-input-number>
                    </n-flex>
                    <n-flex>
                      右边距
                      <n-input-number :min="40" :max="160" :step="5" v-model:value="paperMarginRight"
                        @change="updatePageMargin"></n-input-number>
                    </n-flex>
                  </n-flex>
                </n-flex>
                <n-flex vertical><span>页眉页脚</span>
                  <n-flex>
                    <n-flex>
                      页眉
                      <n-input-number :min="50" :max="200" :step="5" v-model:value="paperMarginTop"
                        @change="updatePageMargin"></n-input-number>
                    </n-flex>
                    <n-flex>
                      页脚
                      <n-input-number :min="50" :max="200" :step="5" v-model:value="paperMarginBottom"
                        @change="updatePageMargin"></n-input-number>
                    </n-flex>
                  </n-flex>
                </n-flex>

              </n-flex>
            </n-card>
            <!-- 文稿格式 -->
            <n-card v-show="activePlane" style="height: 100%">
              <n-flex vertical :size="[0, 25]">
                <n-flex>
                  <n-select v-model:value="titleValue" :options="titleOptions" @update:value="titleSelect" clearable
                    placeholder="定义标题" />
                </n-flex>
                <n-flex>
                  <n-select v-model:value="valuefont" :options="fontoptions" @update:value="onblur"
                    style="width: 100px;" placeholder="定义字体" clearable />
                  <n-select v-model:value="valuesize" :options="dffsize" @update:value="onsize" style="width: 100px;"
                    placeholder="定义字号" clearable />
                </n-flex>
                <n-space>
                  <n-button-group size="small">
                    <n-button type="default" round @click="bold">
                      <template #icon>
                        <n-icon>
                          <SvgIcon iconClass="zitijiacu" />
                        </n-icon>
                      </template>
                    </n-button>
                    <n-button type="default" @click="italic">
                      <template #icon>
                        <n-icon>
                          <SvgIcon iconClass="zitixieti" />
                        </n-icon>
                      </template>
                    </n-button>
                    <n-button type="default" @click="underline">
                      <template #icon>
                        <n-icon>
                          <SvgIcon iconClass="zitixiahuaxian" />
                        </n-icon>
                      </template>
                    </n-button>

                    <n-button type="default" round @click="delete_line">
                      <template #icon>
                        <n-icon>
                          <SvgIcon iconClass="a-bianzu3" />
                        </n-icon>
                      </template>
                    </n-button>
                  </n-button-group>
                </n-space>
                <n-space>
                  <n-button-group size="small">
                    <n-button type="default" round @click="alignment(RowFlex.LEFT)">
                      <template #icon>
                        <n-icon>
                          <SvgIcon iconClass="zuoduiqi" />
                        </n-icon>
                      </template>
                    </n-button>
                    <n-button type="default" @click="alignment(RowFlex.CENTER)">
                      <template #icon>
                        <n-icon>
                          <SvgIcon iconClass="juzhongduiqi" />
                        </n-icon>
                      </template>
                    </n-button>
                    <n-button type="default" @click="alignment(RowFlex.RIGHT)">
                      <template #icon>
                        <n-icon>
                          <SvgIcon iconClass="youduiqi" />
                        </n-icon>
                      </template>
                    </n-button>
                    <n-button type="default" round @click="alignment(RowFlex.JUSTIFY)">
                      <template #icon>
                        <n-icon>
                          <SvgIcon iconClass="zuoyouduiqi" />
                        </n-icon>
                      </template>
                    </n-button>
                  </n-button-group>
                </n-space>
                <n-space>
                  <n-button-group size="small">
                    <n-button type="default" round @click="Superscript">
                      <template #icon>
                        <n-icon>
                          <SvgIcon iconClass="zitishangbiao" />
                        </n-icon>
                      </template>
                    </n-button>
                    <n-button type="default" round @click="Subscript">
                      <template #icon>
                        <n-icon>
                          <SvgIcon iconClass="zitixiabiao" />
                        </n-icon>
                      </template>
                    </n-button>
                  </n-button-group>
                </n-space>
                <n-flex :size="1">
                  <div class="my-title">文本颜色:</div>
                  <n-color-picker v-model="textColor" :show-alpha="false" :modes="['hex']"
                    :on-update:value="editTextColor" style="width: 100px;" />
                </n-flex>
              </n-flex>
            </n-card>
          </div>
        </n-flex>
      </n-flex>
    </n-flex>
  </n-card>
</template>

<style scoped>
.flowsss {
  overflow: scroll;
  height: calc(100vh - 230px);
}

.flowsss::-webkit-scrollbar {
  display: none;
}

.btntools {
  font-size: 24px;
  margin: 2px;
}

.my-title {
  font-size: small;


}

.text-color {
  width: 50px;
  height: 20px;
  background-color: black;
}

.annotationStyles {
  width: calc(100vw / 9);
  height: 620px;
  border: 0;
  overflow-y: auto;
}

.annotationStyles::-webkit-scrollbar {
    /* 滚动条的宽度 */
    width: 0;
}
</style>
